Apply a style to multiple elements at once by adding a class. Here highlighting selected list items with a single class addition:
Html :
<button id="highlightButton">Highlight Items</button>
<ul id="itemList">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
Javascript:
<script>
document.getElementById('highlightButton').addEventListener('click', () => {
const items = document.querySelectorAll('#itemList li');
items.forEach(item => {
item.classList.add('highlight');
});
});
</script>
You Might Also Like
Inject a Script into Document Head or Body Tags
You can inject js script into the document head dynamically like this : ``` const basicScript = do...
Remove Multiple DOM Elements
Use a loop to detach elements and then remove them all at once. ``` const elementsToRemove = docum...